package com.scs.application.modules.upms.login.strategy;

import com.alibaba.fastjson.JSONObject;
import com.scs.application.modules.upms.security.integration.authenticator.WxmpAuthenticator;
import com.google.common.collect.Maps;
import com.scs.application.modules.upms.login.token.WxmpAccessToken;
import com.scs.application.modules.upms.dto.LoginDTO;
import com.scs.application.modules.upms.dto.WxmpLoginDTO;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 */
@Slf4j
@Component
public class WxmpLoginStrategy implements LoginStrategy<WxmpLoginDTO, WxmpAccessToken> {

    @Autowired
    private UserService userService;

    @Override
    public boolean isSupport(LoginDTO loginDTO) {
        return loginDTO instanceof WxmpLoginDTO;
    }

    @Override
    public void preLogin(WxmpLoginDTO loginDTO) {

    }

    @Override
    public Map<String, Object> getParameterMap(WxmpLoginDTO loginDTO) {
        HashMap<String, Object> params = Maps.newHashMap();

        params.put("client_id", "server");
        params.put("client_secret", "123456");
        params.put("grant_type", "password");
        params.put("username", loginDTO.getOpenId());
        params.put("password", loginDTO.getOpenId());
        params.put("auth_type", WxmpAuthenticator.OAUTH_TYPE);
        return params;
    }

    @Override
    public WxmpAccessToken buildToken(JSONObject resp) {
        String loginKey = resp.getString("login_key");

        User user = userService.findByLoginKey(loginKey);
        String accessToken = resp.getString("access_token");

        return (WxmpAccessToken) new WxmpAccessToken()
                        .setNickname(user.getNickname())
                        .setUserId(user.getId())
//                .setOpenId(dto.getOpenId())
                .setAccessToken(accessToken)
                .setExpiresIn(resp.getLong("expires_in"))
                .setJti(resp.getString("jti"))
                        .setLoginKey(user.getLoginKey());
    }
}
